<template>
  <button v-if="!token && openType==='getUserInfo'" class="open-type-btn" open-type="getUserInfo" lang="zh_CN" @getuserinfo="bindGetUserInfo" @click.stop="clickBtn"></button>
  <button v-else-if="openType==='contact'" class="open-type-btn" open-type="contact" :session-from="sessionFrom" @click.stop="clickBtn"></button>
  <button v-else-if="!(userInfo && userInfo.isBindMobile) && openType==='getPhoneNumber'" class="open-type-btn" open-type="getPhoneNumber" @getphonenumber="bindGetPhoneNumber" @click.stop="clickBtn"></button>
  <button v-else-if="openType!=='getUserInfo' && openType!=='getPhoneNumber'" :data-id="btnId" class="open-type-btn" :open-type="openType" @click.stop="clickBtn"></button>
</template>
<script>
import { sobotMicro, sobotService } from '@/plugins/sobot'
import { bindInviteCode } from '@/utils/navigateTo'
import { setClipboardData } from '@/utils/tools'
import { mapState } from 'vuex'
import { requestOpenId,getMiniOpenId } from '@/utils/tools.js'
export default {
  name: '',
  props: {
    openType: {
      type: String,
      default: 'getUserInfo' // 开放能力类型，默认获取用户信息
    },
    option: {
      type: Object,
      default: null // 分享时配置信息
    },
    failMsg: {
      type: String,
      default: '' // 拒绝授权时的提示信息
    },
    goods: {
      type: Object,
      default: null // 商品item, openType为contact时需要传
    },
    btnId: {
      type: String,
      default: '' // 拒绝授权时的提示信息
    }
  },
  data() {
    return {
      sessionFrom: '',
      requestWxTime: 0
    }
  },
  computed: {
    ...mapState([
      'token',
      'userInfo'
    ])
  },
  created() {
    if (this.openType === 'contact') {
      this.sessionFrom = sobotMicro(this.goods)
    }
    this.requestWxTime = 0
  },
  methods: {
    clickBtn() {
      this.$emit('openTypeClick')
      // #ifdef H5
      // To Do ...
      console.log('click', this.openType, 6666)
      if (this.openType === 'contact') {
        if (this.$Bridge.isInApp) {
          this.$Bridge.callHandler({
            type: 'service',
            data: this.goods
          })
        } else {
          sobotService(this.goods, 'navigate')
        }
      } else if (this.openType === 'share') {
        if (this.$Bridge.isInWeChat) {
          uni.showToast({
            title: '点击右上角进行分享操作',
            icon: 'none',
            duration: 1500
          })
        } else if (this.option) {
          if (this.$Bridge.isInApp) {
            this.$Bridge.callHandler({
              type: 'share',
              data: this.option
            })
          } else {
            setClipboardData({
              data: this.option.share_url,
              success: () => {
                uni.showToast({
                  title: '链接已复制，去分享给朋友吧',
                  icon: 'none',
                  duration: 1500
                })
              }
            })
          }
        }
      }
      this.$emit('openCallBack', this.openType)
      // #endif
      // #ifdef MP-WEIXIN
      if (this.openType === 'openSetting') {
        this.$emit('openCallBack', this.openType)
      }
      // #endif
    },
    bindGetUserInfo(e) {
      if (e.mp.detail.userInfo) {
        this.toMPLogin(e.mp.detail)
      } else {
        uni.showToast({
          title: this.failMsg || `需要您的授权才能登录`,
          icon: 'none'
        })
      }
    },
    async bindGetPhoneNumber({ detail }) {
      if (detail.encryptedData) {
        uni.login({
          provider: 'weixin',
          success: async(loginRes) => {
            const res = await this.$api.commonApi.bindPhone({
              encryptedData: detail.encryptedData,
              iv: detail.iv,
              code: loginRes.code
            })
            this.$store.dispatch('SET_USER', {
              token: this.token,
              userInfo: { ...this.userInfo, isBindMobile: 1, mobile: res.data }
            })
            this.$emit('openCallBack', res.data)
          }
        })
      } else {
        uni.showToast({
          title: this.failMsg || `需要您的授权才能继续操作`,
          icon: 'none'
        })
      }
    },
    toMPLogin(detail) { // 微信小程序登录
      // login success
      const { userInfo, encryptedData, iv } = detail
      this.requestWxTime++
      uni.login({
        provider: 'weixin',
        success: async(loginRes) => {
          const res = await this.$api.loginApi.wechatLogin({
            code: loginRes.code,
            encryptedData,
            iv
          })
          if (res.success) {
            if (!res.data.unionid) {
              if (this.requestWxTime < 10) {
                this.toMPLogin(detail)
              } else {
                uni.showToast({
                  title: '登录失败，请重试，或使用手机号登录',
                  icon: 'none'
                })
              }
              return
            }
            if (res.data.user) {
              this.$store.dispatch('SET_USER', {
                token: res.data.token,
                userInfo: res.data.user
              })
              bindInviteCode(this, res.data)
              setTimeout(() => {
                getMiniOpenId();//获取小程序openId
              }, 500)
            } else {
              uni.setStorage({
                key: 'wechat_temp_info',
                data: {
                  open_id: res.data.open_id,
                  nickname: userInfo.nickName,
                  head_img: userInfo.avatarUrl,
                  union_id: res.data.unionid
                }
              })
              this.$navigateTo('/pages/login/mobile?type=bind', {}, 'redirectTo')
            }
            // this.postLocation()
            this.$emit('openCallBack', res.data)
          }
        }
      })
    },
    postLocation() {
      uni.getStorage({
        key: 'biXuanLocation',
        success: async({ data }) => {
          const res = await this.$api.commonApi.postLocation(data)
          console.log(data, res)
        }
      })
    }
  }
}
</script>
<style lang="scss">
.open-type-btn{
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
  opacity: 0;
}
</style>
